﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Collections;
using EpicsJecketClient;
using System.Text.RegularExpressions;
using jtext_EpicsClient;

namespace EJClientTester
{
    
    public partial class Form1 : Form
    {
        bool Running;
        bool isByte;
        EJClient myEjClient;
        object msg;
        public Form1()
        {
            InitializeComponent();
        }

        #region event handler
        private void Ivk_Arrived(object message)
        {
            msg = message;
            MethodInvoker my_fresh = new MethodInvoker(msgArrived);
            this.BeginInvoke(my_fresh);
        }

        private void Ivk_Acked(object state)
        {
            MethodInvoker my_fresh = new MethodInvoker(msgAcked);
            this.BeginInvoke(my_fresh);
        }
        
        
        /// <summary>
        /// show message when my message is acked.
        /// </summary>
        /// <param name="state">The state.</param>
        private void msgAcked()
        {
            TBrecieve.Text += Environment.NewLine + System.DateTime.Now.ToString() + " message Acked  ";
        }

        /// <summary>
        /// show message whenmessage arriverd
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void msgArrived()
        {
            string StrShow;
            if (isByte == true)
            {
                StrShow = BytesToHexString((byte[])msg, ";");
            }
            else 
            {
                StrShow=(string)msg;
            }
            TBrecieve.Text += Environment.NewLine + System.DateTime.Now.ToString() + "  message Arrived  " + StrShow;
        }

        #endregion


        private void BTConnect_Click(object sender, EventArgs e)
        {
            //not only connect but also create ,ini the server
            //if (Running == false)
            //{
            //    return;
            //}
            if (myEjClient != null)
            {
                return;
            }
            isByte = CBByte1.Checked;
            myEjClient = new EJClient(TBServername.Text , TBClientName.Text, isByte, Convert.ToInt16(TBAckLev.Text));
            myEjClient.OnMessage_Ack += new EJClient.Message_ackHandler(Ivk_Acked); ;
            myEjClient.OnMessage_Arrive+=new EJClient.Message_ArriveHandler(Ivk_Arrived);
            myEjClient.StartClient();
            TMStUpdate.Enabled = true;
            //Running = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void BTDiscon_Click(object sender, EventArgs e)
        {
            //not only disconnect,but also dispose ,drop the client
            TMStUpdate.Enabled = false;
            myEjClient.DisposeServer();
            myEjClient = null;
            
        }

        private void BTSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (isByte == true)
                {
                    byte[] msg;
                    msg=HexStringToBytes(TBsent.Text,";");
                    myEjClient.Msg_send(msg).ToString();
                }
                else
                {
                   myEjClient.Msg_send(TBsent.Text).ToString();
                }
            }
            catch
            {
                MessageBox.Show("message format error");
            }
        }

        #region additionnal
        /// <summary>
        /// make a string that contains many hex numbers splited by spliter to byte[]
        /// </summary>
        /// <param name="HexString">The hex string.</param>
        /// <param name="spliter">The spliter.</param>
        /// <returns></returns>
        public static byte[] HexStringToBytes(string HexString,string spliter)
        {
            byte[] tBytes;
            string[] tVals = Regex.Split(HexString, spliter , RegexOptions.IgnoreCase);
            tBytes = new byte[tVals.Length];
            for (int i = 0; i < tVals.Length; i++)
            {
                tBytes[i] = Convert.ToByte(tVals[i], 16);
            }
            return tBytes;
        }

        /// <summary>
        /// make byte array to a string .
        /// </summary>
        /// <param name="BytesArray">The bytes array.</param>
        /// <param name="spliter">The spliter.</param>
        /// <returns></returns>
        public static string BytesToHexString(byte[] BytesArray, string spliter)
        {
            string StrOut="";
            for (int m = 0; m < BytesArray.Length; m++)
            {
                StrOut=StrOut + (BytesArray[m].ToString("X2") + spliter);
            }
            return StrOut;
        }

        #endregion

        private void TMStUpdate_Tick(object sender, EventArgs e)
        {
            //connection states
            int tStr;    //the hard ware state
            tStr = (int)myEjClient.ClientStatus;
            //tStr = -2;
            switch (tStr)
            {
                case -1:
                    {
                        LBConnectionStatus.Text = "No Reply";
                        break;
                    }
                case -2:
                    {
                        LBConnectionStatus.Text = "Disconnected";
                        break;
                    }
                case 0:
                    {
                        LBConnectionStatus.Text = "Connected";
                        break;
                    }
                case 2:
                    {
                        LBConnectionStatus.Text = "Busy";
                        break;
                    }
                default:
                    {
                        LBConnectionStatus.Text = "Error";
                        break;
                    }

            }
        }



    }
}
